package com.lanlian.cayman.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lanlian.cayman.R;
import com.lanlian.cayman.activity.KLineActivity;
import com.lanlian.cayman.adapter.TradeEntrustAdapter;
import com.lanlian.cayman.proto.ProtoManager;
import com.lanlian.cayman.socket.MySocketManager;
import com.lanlian.cayman.socket.SocketCallImpl;
import com.lanlian.cayman.utils.VolleyRequestUtils;
import com.lanlian.commonlib.base.BaseActivity;
import com.lanlian.commonlib.base.BaseLazyFragment;
import com.lanlian.commonlib.bean.BaseResponse;
import com.lanlian.commonlib.bean.EntrustDetailsInfo;
import com.lanlian.commonlib.bean.ReqTradeEntrust;
import com.lanlian.commonlib.bean.RespEntrustDetails;
import com.lanlian.commonlib.event.EventCode;
import com.lanlian.commonlib.event.EventMessage;
import com.lanlian.commonlib.network.INetWorkCallback;
import com.lanlian.commonlib.util.EventBusUtils;
import com.lanlian.uikit.ActionItem;
import com.lanlian.uikit.CustomBottomSheetDialog;
import com.oms.rpc.protobuf.CancelOrderInfo;
import com.oms.rpc.protobuf.CancelOrderReq;
import com.oms.rpc.protobuf.CancelOrderResp;
import com.oms.rpc.protobuf.OMSTradeReq;
import com.oms.rpc.protobuf.OMSTradeRsp;
import com.oms.rpc.protobuf.RequestInfo;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;

/**
 * <pre>
 *     author : huxiaobo
 *     e-mail : huxiaobo@xlanlian.com
 *     date   : 2018/8/14 16:51
 *     desc   : 交易-委托TAB
 *     version: 1.0
 * </pre>
 */
public class TradeEntrustFragment extends BaseLazyFragment {

    private RecyclerView mRecycleView;
    private SmartRefreshLayout mLayRefresh;

    public ArrayList<EntrustDetailsInfo> mList = new ArrayList<>();
    private TradeEntrustAdapter mAdapter;
    private boolean mIsFirst = true;

    private long time;

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        if (!mIsFirst && isVisibleToUser) {
            if (System.currentTimeMillis() - time > 10000) {
                mLayRefresh.autoRefresh();
            }
        }
        super.setUserVisibleHint(isVisibleToUser);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_trade_entrust, null);
        initView(view);
        setListeners();
        initAdapter();
        return view;
    }

    @Override
    protected void loadData() {
        mIsFirst = false;
        mLayRefresh.autoRefresh();
    }

    @Override
    protected void initView(View view) {
        super.initView(view);
        mRecycleView = view.findViewById(R.id.recycle_view);
        mLayRefresh = view.findViewById(R.id.lay_refresh);
    }

    @Override
    protected void setListeners() {
        super.setListeners();
        mLayRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                EventBusUtils.post(new EventMessage(EventCode.EVENT_FUNDS_REFRESH));
                getEntrustDetails();
            }
        });
    }

    private void initAdapter() {
        mAdapter = new TradeEntrustAdapter(R.layout.adapter_trade_entrust, mList);
        mRecycleView.setAdapter(mAdapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        mRecycleView.setLayoutManager(linearLayoutManager);
        mAdapter.bindToRecyclerView(mRecycleView);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int pos) {
                CustomBottomSheetDialog dialog = new CustomBottomSheetDialog(getActivity(), "请选择");
                if ("1".equals(mList.get(pos).getcOrderStatus()) || "2".equals(mList.get(pos).getcOrderStatus())
                        || "3".equals(mList.get(pos).getcOrderStatus()) || "4".equals(mList.get(pos).getcOrderStatus())
                        || "6".equals(mList.get(pos).getcOrderStatus())) {
                    dialog.addAction(new ActionItem("撤单"));
                }
                dialog.addAction(new ActionItem("K线图"));
                dialog.setOnItemClickListener(new CustomBottomSheetDialog.OnItemOnClickListener() {
                    @Override
                    public void onItemClick(ActionItem item, int position) {
                        switch (item.mTitle) {
                            case "撤单":
                                int id = mList.get(pos).getlOrderNo();
                                cancleOrder(id);
                                break;
                            case "K线图":
                                startActivity(new Intent(getActivity(), KLineActivity.class)
                                        .putExtra("name", mList.get(pos).getContractName())
                                        .putExtra("id", mList.get(pos).getVcContractCode()));
                                break;
                            default:
                                break;
                        }
                    }
                });
                dialog.showDialog();
            }
        });
    }

    public boolean iscancleAll() {
        boolean b = false;
        for (EntrustDetailsInfo entrustDetailsInfo : mList) {
            if (entrustDetailsInfo.getcOrderStatus().equals("5") || entrustDetailsInfo.getcOrderStatus().equals("7") ||
                    entrustDetailsInfo.getcOrderStatus().equals("9") || entrustDetailsInfo.getcOrderStatus().equals("a")) {
                continue;
            }
            b = true;
        }
        return b;
    }

    public void cancleAll() {
        OMSTradeReq.Builder builder_oms = OMSTradeReq.newBuilder();
        ProtoManager pm = new ProtoManager();
        RequestInfo.Builder builder = pm.getInitRequestInfo();
        builder.setLRequreId(6001);
        builder_oms.setRequestInfo(builder);
        CancelOrderReq.Builder builder3 = CancelOrderReq.newBuilder();
        CancelOrderInfo.Builder builder_cancle = null;
        EntrustDetailsInfo ei = null;
        for (int i = 0; i < mList.size(); i++) {
            ei = mList.get(i);
            if (ei.getcOrderStatus().equals("5") || ei.getcOrderStatus().equals("7") ||
                    ei.getcOrderStatus().equals("9") || ei.getcOrderStatus().equals("a")) {
                continue;
            }
            builder_cancle = pm.getInitCancelOrderInfo();
            builder_cancle.setLOrderNo(ei.getlOrderNo());
            builder3.addCancelInfo(builder_cancle);
            builder_oms.setCancelorderReq(builder3);
        }
        OMSTradeReq om = builder_oms.build();

        SocketCallImpl sc = new SocketCallImpl((BaseActivity) getActivity()) {
            @Override
            public void message(byte[] data) {
                try {
                    OMSTradeRsp oms = OMSTradeRsp.parseFrom(data);
                    if (oms.getRequestStatus() == 0) {
                        CancelOrderResp cr = oms.getCancelorderResp();
                        if (cr.getErrcode() == 0) {
                            Toast.makeText(getActivity(), "撤单请求成功！", Toast.LENGTH_LONG).show();
                            EventBusUtils.post(new EventMessage(EventCode.EVENT_POSITION_REFRESH));
                            EventBusUtils.post(new EventMessage(EventCode.EVENT_ENTRUST_REFRESH));
                            EventBusUtils.post(new EventMessage(EventCode.EVENT_FUNDS_REFRESH));
                        } else {
                            showToast(cr.getErrmsg());
                        }
                    } else {
                        showToast(oms.getStatusInfo());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        MySocketManager ms = new MySocketManager();
        ms.sendData(om.toByteArray(), sc);
    }

    /**
     * 撤单
     *
     * @param id 订单编号
     */
    private void cancleOrder(int id) {
        BaseActivity context = (BaseActivity) getActivity();
        try {
            ProtoManager pm = new ProtoManager();
            CancelOrderInfo.Builder cb = pm.getCancelOrderInfo();
            cb.setLOrderNo(id);
            OMSTradeReq.Builder oms = pm.getRequst(2);
            OMSTradeReq om = oms.build();
            SocketCallImpl sc = new SocketCallImpl(context) {
                @Override
                public void message(byte[] data) {
                    try {
                        OMSTradeRsp oms = OMSTradeRsp.parseFrom(data);
                        if (oms.getRequestStatus() == 0) {
                            CancelOrderResp cr = oms.getCancelorderResp();
                            if (cr.getErrcode() == 0) {
                                Toast.makeText(context, "撤单请求成功！", Toast.LENGTH_LONG).show();
                                EventBusUtils.post(new EventMessage(EventCode.EVENT_POSITION_REFRESH));
                                EventBusUtils.post(new EventMessage(EventCode.EVENT_ENTRUST_REFRESH));
                                EventBusUtils.post(new EventMessage(EventCode.EVENT_FUNDS_REFRESH));
                            } else {
                                showToast(cr.getErrmsg());
                            }
                        } else {
                            showToast(oms.getRequestStatus() + ":" + oms.getStatusInfo());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            MySocketManager ms = new MySocketManager();
            ms.sendData(om.toByteArray(), sc);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getEntrustDetails() {
        VolleyRequestUtils.getInstance().getTradeEntrust(this.toString(), new ReqTradeEntrust(),
                new INetWorkCallback() {
                    @Override
                    public void onSuccess(Object response) {
                        time = System.currentTimeMillis();
                        mLayRefresh.finishRefresh();
                        RespEntrustDetails respEntrustDetails = (RespEntrustDetails) response;
                        mList = respEntrustDetails.getDataList();
                        mAdapter.setNewData(mList);
                    }

                    @Override
                    public void onFail(BaseResponse baseResponse) {
                        mLayRefresh.finishRefresh();
                        showToast(baseResponse.getMsg());
                    }
                });
    }

    @Override
    protected boolean isRegisteredEventBus() {
        return true;
    }

    @Override
    public void onReceiveEvent(EventMessage event) {
        super.onReceiveEvent(event);
        switch (event.getCode()) {
            case EventCode.EVENT_ENTRUST_REFRESH:
            case EventCode.EVENT_LOGIN_REFRESH:
                getEntrustDetails();
                break;
            default:
                break;
        }
    }

}
